/*
 *  Copyright (C) 2012 Компания ВИТ. web: http://diasled.ru Е-mail:  vit@diasled.ru
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package ru.apertum.diasled.forms;

import com.jogamp.newt.event.KeyEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.TableCellRenderer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.XYDataset;
import ru.apertum.diasled.redactor.SensorDraw;
import ru.apertum.diasled.redactor.TarTableModel;

/**
 * Редактор таблицы тарировки (255 значений давления на каждый датчик)
 * @author Evgeniy Egorov
 */
public class FRedactorTar extends javax.swing.JDialog {

    private boolean result = false;

    public boolean isOK() {
        return result;
    }

    public static FRedactorTar getInstance() {
        FRedactorTarHolder.INSTANCE.result = false;
        return FRedactorTarHolder.INSTANCE;
    }

    private static class FRedactorTarHolder {

        private static final FRedactorTar INSTANCE = new FRedactorTar(null, true);
    }

    /** Creates new form FRedactorTar */
    private FRedactorTar(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        try {
            setIconImage(ImageIO.read(DiasledView.class.getResource("/ru/apertum/diasled/forms/resources/redactor.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }

        // свернем по esc
        getRootPane().registerKeyboardAction(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                result = false;
                setVisible(false);
            }
        },
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);

        tableTar.setModel(new TarTableModel(null));
        tableTar.setDefaultRenderer(Short.class, new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                final JLabel l = new JLabel("" + value);
                l.setFont(new Font("Arial", 2, 12));
                l.setOpaque(true);
                l.setBackground(CLR);
                l.setHorizontalAlignment(JLabel.CENTER);
                return l;
            }
        });
    }
    private static final Color CLR = new Color(240, 240, 240);

    public void loadConfig(final SensorDraw sensor) {
        setTitle("Редактор тарировочных параметров сенсора. Логический номер " + sensor.getLogicalNum());
        ((TarTableModel) (tableTar.getModel())).setTars(sensor.getTarData());
        ((TarTableModel) (tableTar.getModel())).fireTableDataChanged();

        XYDataset data = new AbstractXYDataset() {

            @Override
            public int getSeriesCount() {
                return 1;
            }

            @Override
            public Comparable getSeriesKey(int i) {
                return 1;
            }

            @Override
            public int getItemCount(int i) {
                return 256;
            }

            @Override
            public Number getX(int i, int i1) {
                return i1;
            }

            @Override
            public Number getY(int i, int i1) {
                return ((TarTableModel) (tableTar.getModel())).getTars().get(i1);
            }
        };

        JFreeChart chart = ChartFactory.createXYLineChart(
                null,
                "Код с датчика",
                "Давление г/см2",
                data,
                PlotOrientation.VERTICAL,
                false, // legend?
                false, // tooltips?
                false // URLs?
                );
        chart.setBorderVisible(false);
        ((TarTableModel) (tableTar.getModel())).setChart(chart);

        panelChart.removeAll();
        int h = 250;
        ChartPanel cp = new ChartPanel(chart, 300, h, 100, h, 1920, h + 500, true, true, false, false, true, false);
        GridLayout l = new GridLayout(1, 1);
        panelChart.setLayout(l);
        panelChart.add(cp);
    }

    public void saveConfig(SensorDraw sensor) {
        sensor.setTarData(((TarTableModel) (tableTar.getModel())).getTars());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonCancel = new javax.swing.JButton();
        buttonOK = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableTar = new javax.swing.JTable();
        panelChart = new javax.swing.JPanel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getResourceMap(FRedactorTar.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        buttonCancel.setText(resourceMap.getString("buttonCancel.text")); // NOI18N
        buttonCancel.setName("buttonCancel"); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        buttonOK.setText(resourceMap.getString("buttonOK.text")); // NOI18N
        buttonOK.setName("buttonOK"); // NOI18N
        buttonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOKActionPerformed(evt);
            }
        });

        jSplitPane1.setDividerLocation(450);
        jSplitPane1.setDividerSize(8);
        jSplitPane1.setContinuousLayout(true);
        jSplitPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tableTar.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableTar.setCellSelectionEnabled(true);
        tableTar.setName("tableTar"); // NOI18N
        jScrollPane1.setViewportView(tableTar);
        tableTar.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tableTar.columnModel.title0")); // NOI18N
        tableTar.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tableTar.columnModel.title1")); // NOI18N
        tableTar.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tableTar.columnModel.title2")); // NOI18N
        tableTar.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tableTar.columnModel.title3")); // NOI18N

        jSplitPane1.setLeftComponent(jScrollPane1);

        panelChart.setName("panelChart"); // NOI18N

        javax.swing.GroupLayout panelChartLayout = new javax.swing.GroupLayout(panelChart);
        panelChart.setLayout(panelChartLayout);
        panelChartLayout.setHorizontalGroup(
            panelChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 725, Short.MAX_VALUE)
        );
        panelChartLayout.setVerticalGroup(
            panelChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 541, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(panelChart);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(1015, Short.MAX_VALUE)
                .addComponent(buttonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(buttonCancel)
                .addContainerGap())
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1184, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancel)
                    .addComponent(buttonOK))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        result = true;
        setVisible(false);
    }//GEN-LAST:event_buttonOKActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        result = false;
        setVisible(false);
    }//GEN-LAST:event_buttonCancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonOK;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel panelChart;
    private javax.swing.JTable tableTar;
    // End of variables declaration//GEN-END:variables
}
